<template>
        <el-drawer size="50%" v-model="drawerVisible" title="物料清单">
        <div>
            <div class="pageTableButView bottoms"><el-button :icon="Plus" type="primary"  @click="handleAddRow">新建</el-button></div>

            <el-table :data="processList" style="width: 100%">
                <el-table-column prop="materialId" label="物料名称" >
                    <template #default="scope">
                        {{ getTypeName(scope.row.materialId) }}
                    </template>
                </el-table-column>
                <el-table-column prop="count" label="数量" ></el-table-column>
                <el-table-column label="操作" width="180">
                    <template #default="{ row }">
                        <el-button type="text" @click="handleEditRow(row)">编辑</el-button>
                        <el-button type="text" @click="handleDeleteRow(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-dialog v-model="modalVisible" title="操作" width="500">
                <el-form :model="form" label-width="80px">
                    <el-form-item label="物料名称">
                        <!-- 替换 el-input 为 el-select -->
                        <el-select v-model="form.materialId" placeholder="请选择物料名称">
                            <el-option v-for="item in materialList" :key="item.id" :label="item.materialName"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="数量">
                        <el-input v-model="form.count"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="modalVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitForm">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </el-drawer>
</template>


<script lang="ts" setup>
import { defineProps, watch, ref, onMounted } from 'vue';
import { ElMessage, ElDialog, ElMessageBox } from 'element-plus';
import { getPageApi, materialAllApi, editApi, addApi, deleteApi } from '@/api/baseData/productBOM';
import { useProductBOMData } from '@/hooks/baseData/productBOM';
import { Edit, Delete, Plus, SetUp } from '@element-plus/icons-vue';

const {
    handleBOMAssociation,
    currentItem,
    drawerBOMData
} = useProductBOMData();

const props = defineProps<{
    visible: boolean;
    data: any;
    currentItem: any;
}>();

const drawerVisible = ref(false);
const currentItemList = ref({});
watch(props, (newProps) => {
    drawerVisible.value = newProps.visible;
    currentItemList.value = newProps.currentItem;
    if (newProps.visible) {
        fetchProcessList();
        materialFetch();
    }
    console.log('Props updated:', newProps, currentItem.value);
});

watch(currentItemList, (newProps) => {
    console.log('Props updated:', newProps);

    fetchProcessList();
    materialFetch();
});

const processList = ref<any[]>([]);
const materialList = ref<any[]>([]);

const materialFetch = () => {
    materialAllApi({}).then((res) => {
        materialList.value = res.data;
    });
};
const getTypeName = (type:string) => {
    const name = materialList.value.find((item: any) => item.id === type);
    return name ? name.materialName : '';
};
const handleAddRow = () => {
    showModal('新建');
};

const handleEditRow = (row) => {
    showModal('编辑', row);
};

const handleDeleteRow = (row) => {
    showDeleteConfirm(row);
};

const showModal = (title, row = {}) => {
    modalTitle.value = title;
    form.value = { ...row };
    modalVisible.value = true;
};

const showDeleteConfirm = (row) => {
    ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deleteRow(row);
    }).catch(() => {
    });


};

const deleteRow = async (row) => {
    try {
        await deleteApi({ ids: [row.id] });
        ElMessage.success('删除成功');
        fetchProcessList();
    } catch (error) {
        ElMessage.error('删除失败');
    }
};

const submitForm = () => {
    if (modalTitle.value === '新建') {
        addRow();
    } else if (modalTitle.value === '编辑') {
        editRow();
    }
    modalVisible.value = false;
};

const addRow = async () => {
    try {
        await addApi({ ...form.value, materialBomId: currentItemList.value.id });
        ElMessage.success('新建成功');
        fetchProcessList();
    } catch (error) {
        ElMessage.error('新建失败');
    }
};

const editRow = async () => {
    try {
        await editApi(form.value);
        ElMessage.success('编辑成功');
        fetchProcessList();
    } catch (error) {
        ElMessage.error('编辑失败');
    }
};

const modalVisible = ref(false);
const modalTitle = ref('');
const form = ref({ materialId: '', count: 0, id: '' });

watch(modalVisible, (val) => {
    if (!val) {
        form.value = { materialId: '', count: 0, id: '' };
    }
});

const fetchProcessList = async () => {
    try {
        const response = await getPageApi({ materialBomId: currentItemList.value.id, current: 1, pageSize: 100000 });
        if (response.code === 200) {
            processList.value = response.data.records;
        } else {
            ElMessage.error('获取数据失败');
        }
    } catch (error) {
        ElMessage.error('请求失败');
    }
};


</script>
<style scoped>
.bottoms{
    margin-bottom: 10px;
}
</style>
